<!--
  * 分润提现表
  *
  * @Author:    zhoujk
  * @Date:      2025-01-23 04:08:27
-->
<template>
  <a-card size="small" :bordered="false" class="m-b-3">
    <a-row :gutter="16">
      <a-col class="gutter-row" :span="22">
        <a-descriptions :column="4">
          <a-descriptions-item v-for="item in detailConfig['alimini']" :key="item.dataIndex" :label="item.label" v-bind="item.options">{{
            item?.customRender ? item.customRender({ data: form, text: form[item.dataIndex] }) : form[item.dataIndex]
          }}</a-descriptions-item>
        </a-descriptions>
      </a-col>
      <a-col class="gutter-row" :span="2">
        <a-button type="primary" @click="showForm">
          <template #icon>
            <SearchOutlined />
          </template>
          提现
        </a-button>
      </a-col>
    </a-row>
  </a-card>
  <!---------- 查询表单form begin ----------->
  <a-form class="smart-query-form">
    <a-row class="smart-query-form-row">
      <a-form-item label="提现金额" class="smart-query-form-item">
        <a-input style="width: 200px" v-model:value="queryForm.drawAmt" placeholder="提现金额" />
      </a-form-item>
      <a-form-item label="提现日期" class="smart-query-form-item">
        <a-range-picker
          :allowClear="false"
          :inputReadOnly="true"
          v-model:value="queryForm.drawTime"
          :presets="defaultTimeRanges"
          style="width: 220px"
          @change="onChangeCTime"
        />
      </a-form-item>
      <a-form-item label="审核状态" class="smart-query-form-item">
        <a-select v-model:value="queryForm.auditStatus" style="width: 200px" allowClear :options="PROFIT_AUDIT_STATUS" placeholder="请选择审核状态" />
      </a-form-item>
      <a-form-item class="smart-query-form-item">
        <a-button type="primary" @click="onSearch">
          <template #icon>
            <SearchOutlined />
          </template>
          查询
        </a-button>
        <a-button @click="resetQuery" class="smart-margin-left10">
          <template #icon>
            <ReloadOutlined />
          </template>
          重置
        </a-button>
      </a-form-item>
    </a-row>
  </a-form>
  <!---------- 查询表单form end ----------->

  <a-card size="small" :bordered="false" :hoverable="true">
    <!---------- 表格操作行 begin ----------->
    <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block"></div>
      <div class="smart-table-setting-block">
        <!-- <TableOperator v-model="columns" :tableId="null" :refresh="queryData" /> -->
      </div>
    </a-row>
    <!---------- 表格操作行 end ----------->

    <!---------- 表格 begin ----------->
    <a-table size="small" :dataSource="tableData" :columns="columns" rowKey="id" bordered :loading="tableLoading" :pagination="false">
      <!-- <template #bodyCell="{ text, column }"> -->
      <!--<template v-if="column.dataIndex === 'action'">-->
      <!--  <div class="smart-table-operate">-->
      <!--    <a-button @click="showForm(record)" type="link">编辑</a-button>-->
      <!--  </div>-->
      <!--</template>-->
      <!-- </template> -->
    </a-table>
    <!---------- 表格 end ----------->

    <div class="smart-query-table-page">
      <a-pagination
        showSizeChanger
        showQuickJumper
        show-less-items
        :pageSizeOptions="PAGE_SIZE_OPTIONS"
        :defaultPageSize="queryForm.pageSize"
        v-model:current="queryForm.pageNo"
        v-model:pageSize="queryForm.pageSize"
        :total="total"
        @change="queryData"
        @showSizeChange="queryData"
        :show-total="(total) => `共${total}条`"
      />
    </div>

    <ProfitDrawsForm ref="formRef" @reloadList="(queryData(), queryDrawData())" />
  </a-card>
</template>
<script setup>
  import { reactive, ref, onMounted, nextTick, watch, getCurrentInstance } from 'vue'
  import { profitDrawApi } from '/@/api/business/b-agent/profit/profit-draw/profit-draw-api'
  import { PAGE_SIZE_OPTIONS } from '/@/constants/common-const'
  import { smartSentry } from '/@/lib/smart-sentry'
  import TableOperator from '/@/components/support/table-operator/index.vue'
  import DictSelect from '/@/components/business/comment/DataDictionariesSelect.vue'
  import { defaultTimeRanges } from '/@/lib/default-time-ranges'
  import ProfitDrawsForm from './profit-draw-form.vue'
  import dayjs from 'dayjs'
  import { profitAccApi } from '/@/api/business/b-agent/profit/profit-acc/profit-acc-api.js'
  import { REVIEW_STATUS_ENUM } from '/@/constants/business/components/profit-draws-const.js'
  import SmartEnumSelect from '/@/components/framework/smart-enum-select/index.vue'
  import { formatToMoney, selectDictLabel } from '/@/utils/common'

  import {
    PROFIT_AUDIT_STATUS, //审核状态
  } from '/@/constants/dict'
  const { proxy } = getCurrentInstance()
  // ---------------------------- 表格列 ----------------------------
  const detailConfig = ref({
    alimini: [
      {
        label: '累计结算金额（元）',
        dataIndex: 'sumAmt',
        customRender: ({ text }) => formatToMoney(text / 100),
      },
      {
        label: '佣金账户余额（元）',
        dataIndex: 'balanceAmt',
        customRender: ({ text }) => formatToMoney(text / 100),
      },
      {
        label: '可用金额（元）',
        dataIndex: 'availableAmt',
        customRender: ({ text }) => formatToMoney(text / 100),
      },
      {
        label: '累计已提现金额（元）',
        dataIndex: 'drawnedAmt',
        customRender: ({ text }) => formatToMoney(text / 100),
      },
      {
        label: '冻结金额（元）',
        dataIndex: 'freezeAmt',
        customRender: ({ text }) => formatToMoney(text / 100),
      },
      {
        label: '已到账金额（元）',
        dataIndex: 'receivedAmt',
        customRender: ({ text }) => formatToMoney(text / 100),
      },
      {
        label: '累计未结算金额（元）',
        dataIndex: 'unDrawnAmt',
        customRender: ({ text }) => formatToMoney(text / 100),
      },
    ],
  })

  const columns = ref([
    {
      title: '序号',
      dataIndex: 'index',
      customRender: ({ index }) => {
        return (queryForm.pageNo - 1) * queryForm.pageSize + index + 1
      },
    },
    {
      title: '提现日期',
      dataIndex: 'drawTime',
      customRender: (column) => dayjs(column.text).format('YYYY-MM-DD HH:mm:ss'),
      width: 180,
      ellipsis: true,
    },
    {
      title: '期初金额',
      dataIndex: 'sAmt',
      customRender: (column) => formatToMoney(column.text / 100),
      ellipsis: true,
    },
    {
      title: '提现金额',
      dataIndex: 'drawAmt',
      customRender: (column) => formatToMoney(column.text / 100),
      ellipsis: true,
    },
    {
      title: '提现后余额',
      dataIndex: 'afterDrawAmt',
      customRender: (column) => formatToMoney(column.text / 100),
      ellipsis: true,
    },
    {
      title: '手续费',
      dataIndex: 'fee',
      ellipsis: true,
    },
    {
      title: '代扣税费',
      dataIndex: 'holdFee',
      ellipsis: true,
    },
    {
      title: '实际到账金额',
      dataIndex: 'realReciveAmt',
      customRender: (column) => formatToMoney(column.text / 100),
      ellipsis: true,
    },
    {
      title: '状态',
      dataIndex: 'auditStatus',
      customRender: (column) => selectDictLabel(PROFIT_AUDIT_STATUS, column.text),
      ellipsis: true,
    },
    // {
    //   title: '期末金额',
    //   dataIndex: 'eAmt',
    //   customRender: (column) => formatToMoney(column.text / 100),
    //   ellipsis: true,
    // },
    {
      title: '审核失败原因',
      dataIndex: 'eAmt',
      ellipsis: true,
    },
    {
      title: '备注',
      dataIndex: 'remark',
      ellipsis: true,
    },
    // {
    //   title: '操作',
    //   dataIndex: 'action',
    //   fixed: 'right',
    //   width: 90,
    // },
  ])

  // ---------------------------- 查询数据表单和方法 ----------------------------

  const queryFormState = {
    drawAmt: undefined, //提现金额
    drawTime: [dayjs().startOf('month'), dayjs().endOf('month')], //创建时间
    drawTimeBegin: dayjs().startOf('month').valueOf(), //创建时间 开始
    drawTimeEnd: dayjs().endOf('month').valueOf(), //创建时间 结束
    auditStatus: undefined, //审核状态
    drawAuditFlag: false, //审核状态
    pageNo: 1,
    pageSize: 10,
  }
  // 查询表单form
  const queryForm = reactive({ ...queryFormState })
  // 表格加载loading
  const tableLoading = ref(false)
  // 表格数据
  const tableData = ref([])
  // 总数
  const total = ref(0)

  // 重置查询条件
  function resetQuery() {
    let pageSize = queryForm.pageSize
    Object.assign(queryForm, queryFormState)
    queryForm.pageSize = pageSize
    queryData()
  }

  const statusTypeColorArray = ['red', 'blue']
  // 搜索
  function onSearch() {
    queryForm.pageNo = 1
    queryDrawData()
    queryData()
  }

  // 查询数据
  async function queryData() {
    tableLoading.value = true
    try {
      const param = { ...queryForm, drawAmt: queryForm.drawAmt * 100 }
      let queryResult = await profitDrawApi.page(param)
      // queryResult.data.forEach((item) => {
      //   item.sAmt = (item.sAmt / 100).toFixed(2)
      //   item.drawAmt = (item.drawAmt / 100).toFixed(2)
      //   item.eAmt = (item.eAmt / 100).toFixed(2)
      //   item.fee = (item.fee / 100).toFixed(2)
      //   item.holdFee = (item.holdFee / 100).toFixed(2)
      // })
      tableData.value = queryResult.data
      total.value = queryResult.total
    } catch (e) {
      smartSentry.captureError(e)
    } finally {
      tableLoading.value = false
    }
  }
  const form = reactive({
    id: undefined, //分润账户编号
    profitDrawType: undefined, //分润提现
    sumAmt: undefined,
    balanceAmt: undefined,
    availableAmt: undefined,
    drawnedAmt: undefined,
    freezeAmt: undefined,
    receivedAmt: undefined,
    unDrawnAmt: undefined,
  })
  async function queryDrawData() {
    try {
      const queryResult = await profitAccApi.findOne()
      Object.assign(form, queryResult.data)
    } catch (e) {
      smartSentry.captureError(e)
    }
  }

  function onChangeCTime(dates, dateStrings) {
    queryForm.drawTimeBegin = dates[0].startOf('days').valueOf()
    queryForm.drawTimeEnd = dates[1].endOf('days').valueOf()
  }

  onMounted(() => {
    queryData()
    queryDrawData()
  })

  // ---------------------------- 添加/修改 ----------------------------
  const formRef = ref()

  async function showForm() {
    await nextTick()
    if (!formRef.value) {
      return
    }
    const param = {
      availableAmt: form.availableAmt,
      drawStartAmt: form.drawStartAmt,
    }
    formRef.value.show(param)
  }
</script>
